package tech.wetech.admin3.sys.service;

import com.aliyun.oss.OSS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;

@Slf4j
@Service
public class OssService {

  private OSS ossClient;

//  @Value("${aliyun.oss.endpoint}")
//  private String endpoint;

  @Value("${aliyun.oss.bucketName}")
  private String bucketName;
  @Value("${aliyun.oss.filedir}")
  private String filedir;

  public OssService(OSS oss) {
    this.ossClient = oss;
  }

  public String uploadImage(MultipartFile file) {
    String fileName =filedir + System.currentTimeMillis() + "-" + file.getOriginalFilename();
    try (InputStream inputStream = file.getInputStream()) {
      ossClient.putObject(bucketName, fileName, inputStream);
      String s = ossClient.generatePresignedUrl(bucketName, fileName, DateUtils.addDays(new Date(), 365*100)).toString();

      int index = s.indexOf("?Expires=");
      String s_sub = "";
      if (index != -1) {
         s_sub = s.substring(0, index);
      }

      log.info("文件上传成功:{}  {}",s.length(), s);
      log.info("文件上传成功(截取字符串):{}  {}",s_sub.length(), s_sub);

      return s_sub;
    } catch (Exception e) {
      throw new RuntimeException("文件上传失败", e);
    }
  }

}
